﻿using System;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Description;
using Bronze.Components;
using Bronze.Components.RBAC;
using BSF.Attributes;
using BSF.Enums;
using BSF.ServicesResult;
using BSF.SystemConfig;
using BSF.Tool;
using HuntingFishGame.Domain.Model;
using BSF.CacheManager;
using Newtonsoft.Json;
using CacheManager.Core;
using HuntingFishGame.OpenApi;

namespace HuntingFishGame.CustomerApi.Controllers
{
    /// <summary>
    /// 提供APP更新所需要的接口
    /// </summary>
    //[Authorize]
    [RoutePrefix("account")]
    //[ApiDocument(1)]
    public class AccountController : ApiController
    {
        /// <summary>
        /// 验证登录
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="pwd">密码</param>
        /// <param name="devicetype">设备类别</param>
        /// <param name="phonedevice">设备名称</param>
        /// <param name="uniquetag">设备号（用于消息推送）</param>
        /// <param name="realName">姓名</param>
        /// <returns></returns>
        [Route("login"), Compress]//gzip压缩
        [MultiParameterSupport] //可传json数据
        [ResponseType(typeof(ApiResult<UserInfoResponseModel>))]
        public HttpResponseMessage Login(string userName, string pwd, DeviceTypeEnum devicetype = DeviceTypeEnum.Default, string phonedevice = null, string uniquetag = null, string realName = "")
        {
            //UserModel userInfo = null;

            ////防止多次登入
            //var loginTime = SNSServices.LoginCodeService.GetModelByUserName(userName);
            //var hasVerify = loginTime != null && loginTime.ErrorTimes > 7;
            //if (hasVerify)
            //{
            //    if (loginTime.CreatTime > DateTime.Now.AddMinutes(-1))
            //    {
            //        return this.ApiResult(BSFAPICode.NormalError, "错误过多,请一分钟后重试");
            //    }
            //    SNSServices.LoginCodeService.Del(new[] { loginTime.Id });
            //}

            //LoginStatusEnum loginStatus = SNSServices.UserService.Login(userName, pwd, devicetype, phonedevice, uniquetag, out userInfo);
            LoginStatusEnum loginStatus = LoginStatusEnum.OK;
            string userId = "";
            //TODO 获取经纬度
            decimal? latitude = this.Request.GetQueryString("latitude").IsNull() ? null : this.Request.GetQueryString("latitude").ConvertTo<decimal?>();
            decimal? longitude = this.Request.GetQueryString("longitude").IsNull() ? null : this.Request.GetQueryString("longitude").ConvertTo<decimal?>(); ;
            //判断登录验证状态
            if (loginStatus == LoginStatusEnum.OK)
            {
                var user = ApiUtils.Login(userId, realName, longitude, latitude, devicetype);
                return this.ApiResult(user);
            }
            else
            {
                if (loginStatus == LoginStatusEnum.NotFound)
                    return this.ApiResult(BSFAPICode.NormalError, "用户名或密码不正确");
                else if (loginStatus == LoginStatusEnum.Banned)
                    return this.ApiResult(BSFAPICode.NormalError, "账号已经被锁定");
                else
                    return this.ApiResult(BSFAPICode.NormalError, "服务器开小差了，请重试");
            }
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        [Route("logout"), ValidToken, ValidSignature(isCheck: false), Compress]
        [MultiParameterSupport] //可传json数据
        [ResponseType(typeof(ApiResult))]
        public HttpResponseMessage Logout()
        {
            try
            {
                var user = this.Request.GetUserByToken();
                ApiUtils.LoginOut(user.UserId);
                return this.ApiResult("退出成功");
            }
            catch (Exception ex)
            {
                return this.ApiResult("退出成功");
                //return this.ApiResult(BSFAPICode.NormalError, "退出失败");
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        /// <remarks>
        /// 需求：
        /// 微信点击机器解锁，如果没有绑定提示没有账号需要解绑
        /// 绑定多个时，选择一个账号进行解锁，需要游戏这边提供获取绑定账号接口
        /// 需要在3分钟内输入游戏里面的银行密码，如果正确回复解锁成功，需要游戏这边提供根据游戏账号，游戏银行密码解绑接口（公众平台里面回复时使用）
        /// 实现逻辑：
        /// 表 Id,序号，账号，openId，ischeck(是否选择,bit),createTime,updateTime
        /// 获取绑定的多个账号后返回序号，账号，openId(插入到数据库)，
        /// 用户回复序号后，根据openId+序号修改3分钟最新的一条数据的ischecked为true,updateTime为当前时间
        /// 用户输入游戏银行密码后，更新数据库(openId,ischecked，order by updateTime最新一条数据)，并调用游戏的解绑接口
        /// </remarks>
        [Route("getUserAccount"), ValidToken, ValidSignature(isCheck: false), Compress]
        [MultiParameterSupport] //可传json数据
        [ResponseType(typeof(ApiResult))]
        public HttpResponseMessage GetUserAccount()
        {
            try
            {
                
                
                var user = this.Request.GetUserByToken();
                //TODO 根据openId从游戏平台获取绑定账号
                return this.ApiResult("修改成功");
            }
            catch (Exception ex)
            {
                return this.ApiResult(BSFAPICode.NormalError, "修改失败");
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="oldPwd">原密码</param>
        /// <param name="newPwd">新密码</param>
        /// <param name="pwdType">密码类型</param>
        /// <returns></returns>
        [Route("updatePwd"), ValidToken, ValidSignature(isCheck: false), Compress]
        [MultiParameterSupport] //可传json数据
        [ResponseType(typeof (ApiResult))]
        public HttpResponseMessage UpdatePwd(string oldPwd, string newPwd, PwdTypeEnum pwdType = PwdTypeEnum.GamePwd)
        {
            try
            {
                var user = this.Request.GetUserByToken();
                //TODO 传给游戏平台openId,oldPwd,newPwd,pwdType
                return this.ApiResult("修改成功");
            }
            catch (Exception ex)
            {
                return this.ApiResult(BSFAPICode.NormalError, "修改失败");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <returns></returns>
        [ResponseType(typeof(ApiResult))]
        [Route("testcachemanage"), ValidSignature(isCheck: false), Compress] //gzip压缩
        [MultiParameterSupport] //可传json数据
        [ResponseType(typeof(ApiResult))] //返回类型
        public HttpResponseMessage TestCacheManage(string cacheKey)
        {
            try
            {
                var result = "";
                var item = new { id = 1, name = "shenxf", sex = 1 };
                var cacheModel = CacheHelper.GetOrAdd<string>(cacheKey, (key) => { return JsonConvert.SerializeObject(item); }, 3 * 60);
                //var cacheKey = "username_shenxf";
                var prefix = "username";
                var cacheResult = CacheHelper.Get<string>(cacheKey, prefix);
                if (cacheResult == null)
                {
                    result = JsonConvert.SerializeObject(item);
                    //绝对过期,缓存时间5分钟
                    CacheItem<string> info = new CacheItem<string>(cacheKey, prefix, result, ExpirationMode.Absolute, TimeSpan.FromMinutes(5));//Sliding->滑动过期,Absolute->绝对过期
                    CacheHelper.Add(info);//CacheHelper.Remove(cacheKey);//移除缓存
                }
                else
                {
                    result = cacheResult;
                }
                return this.ApiResult(result);
            }
            catch (Exception ex)
            {
                return this.ApiResult(BSFAPICode.NormalError, "失败");
            }
        }

    }
}